package com.lzk.jetpacktest.File

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import com.lzk.jetpacktest.R
import com.lzk.jetpacktest.databinding.ActivityFileTestBinding
import kotlinx.android.synthetic.main.activity_file_test.*
import java.io.*
import java.lang.NullPointerException

class FileTestActivity : AppCompatActivity() {

    companion object{
        private const val FILE_DIRECTORY = "file"
    }

    private lateinit var mBinding: ActivityFileTestBinding
    private var mOldFile: File? = null
    private val mParentPath: String by lazy {
        cacheDir.absolutePath+File.separator+ FILE_DIRECTORY+File.separator
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = DataBindingUtil.setContentView(this,R.layout.activity_file_test)
        mOldFile = createFile()
        tv_rename.text = mOldFile?.absolutePath

        initEvent()
    }

    private fun initEvent(){
        mBinding.btnRename.setOnClickListener {
            mOldFile?.let {
                val newFile = File(mParentPath+"rename.txt")
                val success = renameFile(it,newFile)
                if (success){
                    tv_rename.append("\n")
                    tv_rename.append(newFile.absolutePath)
                }
            }
        }
        mBinding.btnRenameDelete.setOnClickListener {
            val file = File(mParentPath)
            if (file.exists()){
                file.listFiles().forEach {
                    it.delete()
                }
                tv_rename.text = ""
            }
        }
    }

    private fun createFile(): File?{
        var bufferedWriter: BufferedWriter? = null
        try {
            val file = File(mParentPath+"name.txt")
            if (!file.parentFile.exists()){
                file.parentFile.mkdirs()
            }
            if (!file.exists()){
                file.createNewFile()
            }

            bufferedWriter = BufferedWriter(OutputStreamWriter(FileOutputStream(file,true)))
            for (i in 0..10){
                bufferedWriter.write("Hello world!#$i")
                bufferedWriter.newLine()
            }
            return file
        }catch (e: IOException){
            e.printStackTrace()
        }finally {
            bufferedWriter?.let {
                it.flush()
                it.close()
            }
        }
        return null
    }

    private fun renameFile(oldFile: File,newFile: File): Boolean{
        try {
            return oldFile.renameTo(newFile)
        }catch (e: SecurityException){
            e.printStackTrace()
        }catch (e: NullPointerException){
            e.printStackTrace()
        }
        return false
    }


}